<template>
  <el-dialog width="600px" :visible.sync="dialogVisible">
    <div v-loading="loading" style="text-align: center">
      <div>导入数据格式严格按照模板进行数据录入,点击
        <download-button :params="{fileName:'模具信息模板'}" :path="downloadTemplateApiPath" type="text" text="下载模板" />
      </div>
      <el-upload
        drag
        accept=".xls,.xlsx"
        :action="uploadApiPath"
        :headers="headerObj"
        :on-error="errorHandler"
        :before-upload="beforeUpload"
        :on-success="(res, file) => handleUpload(res, file)"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件且不超过100MB</div>
      </el-upload>
    </div>
  </el-dialog>
</template>

<script>

export default {
  name: 'CustomUpload',
  props: {
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    uploadApiPath: {
      type: String,
      default() {
        return ''
      }
    },
    downloadTemplateApiPath: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      headerObj: { 'authorization': window.sessionStorage.getItem('authorization') },
      loading: false
    }
  },
  methods: {
    beforeUpload(file) {
      this.loading = true
      const isLt4M = file.size / 1024 / 1024 < 100
      if (!isLt4M) {
        this.$message.error('上传图片大小不能超过 100MB!')
        return false
      }
    },
    handleUpload(res, file) {
      this.loading = false
      if (res.code === 200) {
        this.$notify.success('导入成功！')
        this.$emit('close')
      } else {
        this.$notify.error(res.message || '导入失败！')
      }
    },
    // 文件上传失败时的钩子
    errorHandler(err) {
      let myError = err.toString()
      myError = myError.replace('Error: ', '')
      myError = JSON.parse(myError)
      this.$notify.error({
        title: '上传失败',
        message: myError.msg
      })
    }
  }
}
</script>

<style scoped>

</style>
